﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class EditIssue : BasePage
    {
        #region Properties
        private List<TeamMember> projectTeamMembers;
        public List<TeamMember> ProjectTeamMembers
        {
            get { return projectTeamMembers; }
            set { projectTeamMembers = value; }
        }

        private Work work;
        public Work Work
        {
            get { return work == null ? new Work ( ) : work; }
            set { work = value; }
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public TeamMemberCollection TeamMembers
        {
            get { return ( TeamMemberCollection ) teamMemberList; }
        }

        public string UrlReferrer
        {
            get
            {
                string urlReferrer = default ( string );

                if ( ViewState [ "UrlReferrer" ] != null )
                    urlReferrer = ( string ) ViewState [ "UrlReferrer" ];
                else if ( Request.UrlReferrer != null )
                    urlReferrer = Request.UrlReferrer.ToString ( );

                return urlReferrer;
            }
            set { ViewState [ "UrlReferrer" ] = value; }
        }

        public double HoursPerDay
        {
            get { return SetupModel.GetHoursPerDay ( SiteCollectionId, ServerRelativeUrl ); }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.Edit;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.Edit;
            Buttons.SaveButton.ControlMode = SPControlMode.Edit;
            Buttons.CancelButton.ControlMode = SPControlMode.Edit;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.EntityType = typeof ( Work );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Work ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.Edit;

            Buttons.SaveButton.ItemId = ItemId;
            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            NavigationSub.DeleteButton.ItemContext = context;
            NavigationSub.DeleteButton.RenderContext = context;

            litTitle.Text = "Edit Issue";

            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Edit Issue";
            }

            ProjectTeamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );
            Work = WorkModel.GetById ( ItemId, SiteCollectionId, ServerRelativeUrl );

            if ( Work != null )
            {
                PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( Work, CurrentUser, SiteCollectionId, ServerRelativeUrl );

                if ( Work.PermissionBitsWork != null && Work.PermissionBitsWork.Count > 0 && Work.PermissionBitsWork [ 2 ] )
                {
                    AddCommandButtons ( );

                    if ( !Page.IsPostBack )
                    {
                        UrlReferrer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString ( ) : ServerRelativeUrl + Constants.ProjectFileUrls.MyWork;//Request.UrlReferrer.ToString();

                        TeamMembers.TeamMembers = ProjectTeamMembers;
                        TeamMembers.SelectedIds = Work.AssignedToList;
                        TeamMembers.ReadOnly = false;

                        PopulateForm ( );
                    }
                    else // to repopulate the attachments attached with Discussion before editing
                    {
                        if (Work.AttachmentList != null)
                            Attachments.SetAttachments(Work.AttachmentList);
                    }
                }
                else
                {
                    Response.Redirect ( Cancel ( ) );
                }
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
        }
        #endregion

        #region Button Events
        protected void btnBackToWork_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( Cancel ( ) );
        }
        #endregion

        #region Methods
        internal override bool Save ( )
        {
            Work.ClearValidationMessages ( );

            if ( Work.PermissionBitsWork [ 2 ] )
            {
                Work.ServerRelativeUrl = ServerRelativeUrl;
                Work.SiteCollectionId = SiteCollectionId;
                Work.ModifiedBy = CurrentUser;
                Work.ModifiedDate = DateTime.Now;

                Work.Title = txtTitle.Text.Trim ( );
                Work.Description = txtDescription.Text;
                Work.StatusNote = txtStatusNote.Text;
                Work.WorkItemType = WorkType.Issue;
                Work.Status = ( StatusType ) int.Parse ( rblStatus.SelectedValue );

                ValidationMessage message = null;

                double txtNumber = 0.0;
                bool success = double.TryParse ( txtAssignWork.Text, out txtNumber );
                Work.AssignedWork = string.IsNullOrEmpty ( txtAssignWork.Text ) ? default ( float ) : success ? ( float ) txtNumber : -1;
                Work.AssignedWork = FormattingHelpers.ConvertToMinutes ( Work.AssignedWork, KiiroMaster.V2Header.Project.TimeMetric, HoursPerDay );

                DateTime dt;

                if ( DateTime.TryParse ( txtEndDate.Text, out dt ) || string.IsNullOrEmpty ( txtEndDate.Text ) )
                {
                    work.EndDate = string.IsNullOrEmpty ( txtEndDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtEndDate.Text );
                }
                else
                {
                    message = new ValidationMessage ( ValidationSeverity.Validation, "End date is not in the correct format. (e.g: 05/17/2007)" );
                    work.EndDateMessage.Add ( message );
                }

                Work.IsHighPriority = chkIsHighPriority.Checked;

                Work.AssignedToList = TeamMembers.GetSelectedIds ( );
                Work.AttachmentList = Attachments.GetAttachments ( );
                Work.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                Work.EditType = EditType.Updated;

                Work.AttachmentList = Attachments.ValidateFileExtension(Work.AttachmentList);
                Work = WorkModel.Save ( Work, SiteCollectionId, ServerRelativeUrl );

                if ( Work.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                    PopulateErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        internal override string Cancel ( )
        {
            string url = String.Format ( "{0}/MyWork.aspx", ServerRelativeUrl );

            if ( !string.IsNullOrEmpty ( UrlReferrer ) && Work.EditType != EditType.Deleted )
                url = UrlReferrer;

            return url;
        }

        internal override void Delete ( )
        {
            Work.EditType = EditType.Deleted;
            Work.ModifiedBy = CurrentUser;
            Work = WorkModel.Save ( Work, SiteCollectionId, ServerRelativeUrl );
            Response.Redirect ( Cancel ( ) );
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsWork [ 3 ] )
            {
                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = "Delete this Issue";
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                string js = "javascript:{0}__doPostBack('ctl00$MainContent$V2NavigationSub$diidIODeleteItem','')";
                btnDelete.OnClientClick = string.Format ( js, "if (confirm('Are you sure that you want to delete this issue?'))" );
                NavigationSub.Commands.Add ( btnDelete );
            }
        }

        private void PopulateForm ( )
        {
            litTitle.Text = litTitle.Text + " - " + work.Title;

            txtTitle.Text = Work.Title;
            chkIsHighPriority.Checked = Work.IsHighPriority;
            txtAssignWork.Text = FormattingHelpers.ConvertFromMinutes ( Work.AssignedWork, KiiroMaster.V2Header.Project.TimeMetric, HoursPerDay ).ToString ( );
            txtDescription.Text = Work.Description;
            txtStatusNote.Text = Work.StatusNote;
            if ( work.EndDate != null && work.EndDate != DateTime.MinValue )
                txtEndDate.Text = FormattingHelpers.DateTimeToDatePickerString ( Work.EndDate );
            rblStatus.SelectedValue = ( ( int ) Work.Status ).ToString ( );


            if ( KiiroMaster.V2Header.Project != null )
            {
                lblTimeUnit.Text = KiiroMaster.V2Header.Project.TimeMetric.ToString ( );
            }

            Attachments.SetAttachments ( Work.AttachmentList );
        }

        private void PopulateErrorMessages ( )
        {
            lblStatusNoteMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.StatusNoteMessage );
            lblStatusNoteMessage.Visible = !string.IsNullOrEmpty ( lblStatusNoteMessage.Text );

            lblDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.DescriptionMessage );
            lblDescriptionMessage.Visible = !string.IsNullOrEmpty ( lblDescriptionMessage.Text );

            lblTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.TitleMessage );
            lblTitleMessage.Visible = !string.IsNullOrEmpty ( lblTitleMessage.Text );

            lblAssignWorkMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.AssignedWorkMessage );
            lblAssignWorkMessage.Visible = !string.IsNullOrEmpty ( lblAssignWorkMessage.Text );

            lblDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( Work.DescriptionMessage );
            lblDescriptionMessage.Visible = !string.IsNullOrEmpty(lblDescriptionMessage.Text);

            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText(Work.AttachmentListMessage);
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Work/EditIssue.aspx.cs $
 * 
 * 18    2/08/10 2:28p Camerons
 * 
 * 17    1/11/10 11:51a Camerons
 * 
 * 16    1/06/10 12:39p Camerons
 * 
 * 15    12/14/09 2:10p Shafia
 * attachments file extensions validation for discussions, tasks, and
 * issues
 * 
 * 14    10/26/09 11:47a Adamw
 * Case 332
 * 
 * 13    21/10/09 11:29a Shafia
 * Added validation that Estimated time is a number before parsing it to
 * float. If not a number it will show a validation error.
 * 
 * 12    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 11    30/09/09 9:57a Shafia
 * 
 * 10    19/08/09 12:16p Camerons
 * Fixed get for UrlReferrer property
 * 
 * 9     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/